package com.biz.primus.ms.base.feign;

import com.biz.primus.base.constant.SoaExceptionFieldNames;
import com.biz.primus.base.exception.BizSilentException;
import feign.Response;
import feign.codec.ErrorDecoder;

import javax.servlet.http.HttpServletResponse;
import java.util.Collection;

/**
 * Created by defei on 9/13/17.
 */
public class PrimusSoaFeignErrorDecoder implements ErrorDecoder {

    private final ErrorDecoder defaultErrorDecoder = new Default();

    @Override
    public Exception decode(String methodKey, Response response) {

        if (response.status() == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
            Collection<String> errorCode = response.headers().get(SoaExceptionFieldNames.ERROR_CODE);
            if (errorCode != null && !errorCode.isEmpty()) {
                Collection<String> errorMsg = response.headers().get(SoaExceptionFieldNames.ERROR_MESSAGE);
                Integer code = Integer.valueOf(errorCode.iterator().next());
                String msg = errorMsg == null ? "" : errorMsg.iterator().next();
                return new MSBusinessException(new BizSilentException(code, msg));
            }
        }
        return defaultErrorDecoder.decode(methodKey, response);
    }
}
